package com.pqtest.api.domain;

import com.pqtest.api.dto.ConnectionDto;
import com.pqtest.api.dto.SimulibraryReportDto;
import com.pqtest.api.dto.SimulibraryDto;
import com.pqtest.api.entity.ConnectionEntity;
import com.pqtest.api.entity.SimulibraryEntity;
import com.pqtest.api.service.ConnectionService;
import com.pqtest.api.utils.DtoEntityTransformer;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

@Component
@Log
public class SimulibraryDomain {
    @Autowired
    ConnectionService connectionService;
    //提交试卷
    public SimulibraryEntity submit(SimulibraryDto simulibraryDto){
        simulibraryDto.setIsDone(1);
        SimulibraryEntity simulibraryEntity = new SimulibraryEntity();
        DtoEntityTransformer.transalte(simulibraryDto,simulibraryEntity);
        return simulibraryEntity;
    }
    //获取考试报表
    public SimulibraryReportDto getReport(SimulibraryDto simulibraryDto, List<ConnectionEntity> connectionEntityList){
        SimulibraryReportDto simuLibraryReportDto = new SimulibraryReportDto();
        int total = 0;
        int right = 0;

        Map<String,List<ConnectionDto>> detail = new HashMap<>();
        Map<String,Integer> detailRate = new HashMap<>();
        for(ConnectionEntity connectionEntity : connectionEntityList){
            total++;
            if(connectionEntity.getIsAnswerRight() == 1){
                right++;
            }
            String path   =  connectionEntity.getItem().getPoint_cate().getPath();
            String section = path.split(" > ")[1];
            //set section
            List<ConnectionDto> previous = detail.get(section);
            if(previous == null){
                previous = new ArrayList<ConnectionDto>();
            }
            ConnectionDto connectionDto = new ConnectionDto();
            DtoEntityTransformer.transalte(connectionEntity,connectionDto);
            previous.add(connectionDto);
            detail.put(section,previous);
        }
        Map<String,Integer> dr = new HashMap<>();
        detail.forEach((k,v) -> {
            int ra = 0;
            dr.put(k,ra);
            for(ConnectionDto vv : v){
                if(vv.getIsAnswerRight() == 1){
                    dr.put(k,++ra);
                }
            }
        });
        simuLibraryReportDto.setDetailRate(dr);
        simuLibraryReportDto.setDetail(detail);
        //random generate between 50 ~ 99
        simuLibraryReportDto.setPassOver((new Random()).nextInt(99-50+1) + 50);
        BigDecimal bd = new BigDecimal(((float)right/total) * 100);
        bd = bd.setScale(0,BigDecimal.ROUND_HALF_UP);
        simuLibraryReportDto.setRightRate(bd.intValue());
        simuLibraryReportDto.setSpentTime(simulibraryDto.getLastStopTime());

        return simuLibraryReportDto;
    }
}
